<?php

namespace plugin\muadmin\app\common\core;

trait BaseController
{
    public function selectpage()
    {
        list($where, $sort, $order, $page, $limit) = $this->buildParameter();
    }
    public function index()
    {
        if($this->request->isAjax()){
            $param = $this->request->all();
            list($where, $sort, $order, $page, $limit) = $this->buildParameter();
            $list_type = !empty($param['list_type'])?$param['list_type']:$this->listType;
//            print_r($sort.PHP_EOL);
//            print_r($order.PHP_EOL);
            if($list_type=='ordinary'){
                $list = $this->model->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
                $res = ['total'=>$list->total(),'rows'=>$list->items()];
            }elseif($list_type=='tree'){
                $list = $this->model->where($where)
                    ->order($sort, $order)
                    ->select()->toArray();
                if(!empty($list)){
                    $list = list_to_tree($list, $this->model->getPk(), $this->pidName, $this->childrenName);
                }
                $res = ['total'=>count($list),'rows'=>$list];
            }
            if($this->indexGetData){
                return $res;
            }
            return $this->success('ok',$res);
        }
        return $this->fetch();
    }

    /**
     * 添加
     * @return \support\Response
     */
    public function add()
    {
        $param = $this->request->all();
        if($this->request->isAjax()){
            $data = $this->param('row');
            if(empty($data)){
                return $this->error('请选择添加项row');
            }
            $has = $this->model->where('name',$data['name'])->find();
            if(!empty($has)){
                return $this->error('规则已存在');
            }
            $res = $this->model->create($data);
            if(!$res){
                return $this->error('保存失败');
            }
            return $this->success("保存成功");
        }
        $this->assignConfig('param',$param);
        return $this->fetch();
    }

    /**
     * 编辑
     * @return \support\Response
     */
    public function edit()
    {
        $ids = $this->param('ids');
        if(empty($ids)){
            return $this->error('请选择编辑项');
        }
        $row = $this->model->where($this->model->getPk(), $ids)
            ->find();
        if(empty($row)){
            return $this->error('数据不存在');
        }
        if($this->request->isAjax()){
            $data = $this->param('row');
            if(empty($data)){
                return $this->error('请选择编辑项row');
            }
            $has = $this->model->where('name',$data['name'])
                ->where($this->model->getPk(),'<>',$ids)
                ->find();
            if(!empty($has)){
                return $this->error('规则已存在');
            }
            $res = $row->save($data);
            if(!$res){
                return $this->error('保存失败');
            }
            return $this->success("保存成功");
        }
        $this->assignConfig('row',$row);
        return $this->fetch();
    }

    /**
     * 删除
     * @return \support\Response
     */
    public function del()
    {
        $data = $this->request->all();
        if(empty($data['ids'])){
            return $this->error('请选择删除项');
        }
        $ids = $data['ids'];
        if(is_string($ids)){
            $ids = explode(',',$ids);
        }
        $res = $this->model->destroy($ids);
        return $this->success('删除成功',['res'=>$res]);
    }

    /**
     * 多选
     * @return \support\Response
     */
    public function multi()
    {
        $data = $this->request->all();
        if(empty($data['ids'])){
            return $this->error('请选择删除项');
        }
        if(empty($data['field'])){
           return $this->error('请选择操作项');
        }
        $field = $data['field'];
        $row = $this->model->where($this->model->getPk(), $data['ids'])
            ->find();
        if(empty($row)){
            return $this->error('数据不存在');
        }
        if(empty($row->$field)){
            $row->$field = 1;
        }else{
            $row->$field = 0;
        }
        $res = $row->save();
        if($res){
            return $this->success('操作成功');
        }
        return $this->error('操作失败');
    }

    /**
     * 构建查询条件
     * @param $whereIsArray
     * @return array
     */
    public function buildParameter($whereIsArray=false)
    {
        $relationSearch = $this->relationSearch;
        $param = $this->request->all();
        $sort = !empty($param['sort'])?$param['sort']:(! empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = !empty($param['order'])?$param['order']:'desc';
        $page = !empty($param['page'])?$param['page']:1;
        $limit = !empty($param['limit'])?$param['limit']:10;
        $where = [];
        $filter = !empty($param['filter'])?$param['filter']:[];
        if(is_string($filter)){
            $filter = json_decode(htmlspecialchars_decode($filter), true);
        }
        $op = !empty($param['op'])?$param['op']:[];
        if(is_string($op)){
            $op = json_decode(htmlspecialchars_decode($op), true);
        }
        foreach ($filter as $k=>$v){
            $sym = isset($op[$k]) ? $op[$k] : ' = ';
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym){
                case ' = ':
                case '=':
                case ' <> ':
                case '<>':
                    $where[] = [$k, $sym, (string) $v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace(' %...%', '', $sym)), "%{$v}%"];
                    break;
                case ' > ':
                case '>':
                case '>=':
                case ' < ':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('$v', ".($relationSearch ? $k : '`'.str_replace('.', '` . `', $k).'`').')';
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    if(is_string($v)){
                        $arr = array_slice(explode(',', $v), 0, 2);
                        if (stripos($v, ',') === false || !array_filter($arr, function($v){
                                return $v != '' && $v !== false && $v !== null;
                            })) {
                            continue 2;
                        }
                    }else{
                        $v = array_filter($v);
                        if(empty($v)){
                            continue 2;
                        }
                        $arr = $v;
                    }

                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? ' <= ' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? ' >= ' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || ! array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? ' <= ' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? ' >= ' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym).' time', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        if($whereIsArray===false){
            if (! empty($where)) {
                $where = function ($query) use ($where) {
                    foreach ($where as $k => $v) {
                        if (is_array($v)) {
                            call_user_func_array([$query, 'where'], $v);
                        } else {
                            $query->where($v);
                        }
                    }
                };
            }
        }


        return [$where, trim($sort), trim($order), $page, $limit];
    }
}